package gazzera.node.core;

import java.io.*;
import java.util.*;

public class Peoples
{
	private Map<String, Person> persons = null;
	private File file;
	
	public Peoples(File mainDir) throws Exception
	{
		file = new File(mainDir, "friends");
		try
		{
		    load();
		}
		catch (Exception e)
		{
		    e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	private void load() throws Exception
	{
		
		if(file.exists())
		{
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
			try
			{
				Object o = ois.readObject();
				Map<String, Person> m = (Map<String, Person>)o;
				for (Person p : m.values())
				{
					p.onlineStatus = OnlineStatus.OFFLINE;
					if (p.status == FriendStatus.FOAF) p.status = FriendStatus.STRANGER;
				}
				persons = m;
			}
			finally
			{
				ois.close();
			}
		}
		else
		{
			persons = new HashMap<String, Person>();
			save();
		}
	}
	public Person get(String hash)
	{
		synchronized (persons)
		{
			return persons.get(hash);
		}
	}
	public Person add(Person p) 
	{
		synchronized (persons)
		{
			persons.put(p.hash, p);
			// save();
			return p;
		}
	}
	public void remove(Person p) throws Exception
	{
		synchronized (persons)
		{
			persons.remove(p.hash);
			// save();
		}
	}
	
	public void save() throws Exception
	{
		synchronized (persons)
		{
			ObjectOutputStream ois = new ObjectOutputStream(new FileOutputStream(file));
			try
			{
				ois.writeObject(persons);
			}
			finally
			{
				ois.close();
			}
		}
	}
	
	public Collection<Person> getAll()
	{
		return Collections.unmodifiableCollection(persons.values());
	}
}
